package resml

import (
	"io"
	"net/url"
	"os"
	"path/filepath"
)

// 文件资源
type FileResource struct {
	uri    *url.URL
	uriStr string
	path   string
	append bool

	etager ETager
}

func NewFileResource(uri *url.URL, etager ETager) *FileResource {
	return &FileResource{
		uri: uri, uriStr: uri.String(),
		path:   filepath.ToSlash(filepath.Clean(uri.Path)),
		etager: etager,
	}
}

func (r *FileResource) Append() {
	r.append = true
}

func (r *FileResource) Uri() string {
	return r.uriStr
}

func (r *FileResource) Meta() (Meta, error) {
	return MetaOfFile(r.path, r.etager)
}

func (r *FileResource) Get() (io.ReadCloser, Meta, error) {
	meta, err := r.Meta()
	if err != nil {
		return nil, nil, err
	}
	fd, err := os.Open(r.path)
	if err != nil {
		return nil, nil, err
	}
	return fd, meta, nil
}

func (r *FileResource) Put(meta Meta, reader io.Reader) error {
	fd, err := FileCreate(r.path, r.append)
	if err != nil {
		return err
	}
	defer fd.Close()
	_, err = io.Copy(fd, reader)
	return err
}

func (r *FileResource) Remove() error {
	return os.Remove(r.path)
}
